package com.ask.utils;

import com.ask.constant.MessageConstant;
import com.ask.exception.BaseException;
import com.ask.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(BaseException.class)
    public Result handleException(BaseException ex) {
        log.error("错误信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex ){
        String message = ex.getMessage(); //获取异常的消息字符串
        /* java.sql.SQLIntegrityConstraintViolationException:
         Duplicate entry 'zhangsan' for key 'employee.idx_username'*/
        if(message.contains("Duplicate entry")){ //判断是否【违反违反唯一约束】异常
            String[] split = message.split(" ");
            String username = split[2];
            String msg = username + MessageConstant.ALREADY_EXIXT;
            return Result.error(msg);
        }
        else return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}